# -*- coding: utf-8 -*-
'''
Created on Mar 24, 2013

@author: LONG HOANG GIANG
'''
from lxml import etree
from PyLib import cleanHTMLEntities, normalizeStr
import re

class Etree():
    
    @staticmethod
    def tostring(node):
        if node == '': return ''
        html = ''
        if '_Element' in type(node).__name__:
            html = Etree.cleanCommentHTMLTag(cleanHTMLEntities(etree.tostring(node, pretty_print=True, encoding='UTF-8', method="html")))
        elif type(node).__name__ == 'list':
            level = 0
            for inode in node:
                html += Etree.tostring(inode)
                if len(node)-1 > level: html += "<p>&nbsp;</p>"
                level += 1
        return html
    
    @staticmethod
    def clean(node):
        if node == None: return
        if '_Element' in type(node).__name__:
            node.getparent().remove(node)
        elif type(node).__name__ == 'list':
            for inode in node:
                Etree.clean(inode)
        return
    
    @staticmethod
    def cleanNode(xpathStr, pNode):
        if type(pNode).__name__ == 'list':
            if len(pNode) == 0: return
            pNode = pNode[0]
        elif '_Element' not in type(pNode).__name__:
            return
        nodes = pNode.xpath(xpathStr)
        for node in nodes:
            try:
                node.getparent().remove(node)
            except:
                continue
    
    @staticmethod
    def cleanNodeNextSibling(node, self_clean=True):
        try:
            if '_Element' in type(node).__name__:
                for inode in node.xpath("./following-sibling::*"):
                    inode.getparent().remove(inode)
                if (self_clean):
                    node.getparent().remove(node)
            elif type(node).__name__ == 'list':
                for inode in node:
                    Etree.cleanNodeNextSibling(inode, self_clean)
        except:
            return False
        return True
    
    @staticmethod
    def cleanNodePreceding(node, self_clean=True):
        try:
            if '_Element' in type(node).__name__:
                for inode in node.xpath("./preceding-sibling::*"):
                    inode.getparent().remove(inode)
                if (self_clean):
                    node.getparent().remove(node)
            elif type(node).__name__ == 'list':
                for inode in node:
                    Etree.cleanNodeNextSibling(inode, self_clean)
        except:
            return False
        return True
    
    @staticmethod
    def cleanCommentHTMLTag(html):
        html = normalizeStr(html)
        html = re.sub(r"<!--(.+)-->", "", html)
        return html
    
    